package com.example.cardgame.model

class CardMatchingGame(val count: Int) {
    var score = 0
        private set

    val cards: MutableList<Card>

    // ✅ 新增：匹配模式（2 或 3）
    var matchMode = 2

    init {
        val deck = Deck()
        cards = mutableListOf()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun reset() {
        val deck = Deck()
        score = 0
        cards.clear()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun cardAtIndex(index: Int): Card {
        return cards[index]
    }

    private val MISMATCH_PENALTY = 2
    private val MATCH_BONUS = 4
    private val COST_TO_CHOOSE = 1

    fun chooseCardAtIndex(index: Int) {
        val card = cardAtIndex(index)
        if (card.isMatched) return

        if (card.isChosen) {
            card.isChosen = false
        } else {
            // 找出当前选中的未匹配卡
            val chosenCards = cards.filter { it.isChosen && !it.isMatched }

            // ✅ 根据模式动态判断何时触发匹配
            if (chosenCards.size == matchMode - 1) {
                val matchScore = card.match(chosenCards.toTypedArray())
                if (matchScore > 0) {
                    score += matchScore * MATCH_BONUS
                    card.isMatched = true
                    for (c in chosenCards) c.isMatched = true
                } else {
                    score -= MISMATCH_PENALTY
                    for (c in chosenCards) c.isChosen = false
                }
                score -= COST_TO_CHOOSE
                card.isChosen = true
            } else {
                score -= COST_TO_CHOOSE
                card.isChosen = true
            }
        }
    }
}
